package com.cmtime.proxy;
/**
 * 通过反射机制实现
 */
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKDynamicProxy implements InvocationHandler{
    
	private Object target;
	public JDKDynamicProxy(Object target){
		this.target = target;
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("前置通知"+method.getName());
		Object obj = method.invoke(target,args);
		System.out.println("后置通知");
		return obj;
	}
	
	public Object getObject(){
		JDKDynamicProxy dynamic = new JDKDynamicProxy(this.target);
		Animal animal = (Animal) Proxy.newProxyInstance(dynamic.getClass().getClassLoader(), this.target.getClass().getInterfaces(), dynamic);
		return animal;
	}
	
	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		for(int i=0;i<1;i++){
			Dog dog = new Dog();
			JDKDynamicProxy jdkProxy = new JDKDynamicProxy(dog);
			Animal animal = (Animal) jdkProxy.getObject();
			animal.work();
		}
		long end = System.currentTimeMillis();
		System.out.println(end - start);
	}
}
